package siec;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Client {
	private String host;

	private int port;

        public Zegar zegarKlient;
                
        public PrintWriter zapis = null;
        
	private String playerID;

	private Socket socket;

	private Connection connection = null;

	public Client(String nick, String host, int port) {
		this.host = host;
		this.port = port;
		this.playerID = nick;
	}

	public boolean start() {
		try {
			socket = new Socket(host, port);
		} catch (Exception ex) {
			return false;
		}

        GregorianCalendar data=new GregorianCalendar();
        String nazwaPliku = "Klient_log_"+data.get(Calendar.YEAR)+"_"+data.get(Calendar.MONTH)+"_"+data.get(Calendar.DAY_OF_MONTH)+"_"+data.get(Calendar.HOUR)+"_"+data.get(Calendar.MINUTE)+"_"+data.get(Calendar.SECOND)+".txt";
        zegarKlient = new Zegar(1);
        try {
            zapis = new PrintWriter(new FileWriter(nazwaPliku, true));
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }  
        data=new GregorianCalendar();   
        zapis.println("Data i czas: "+data.get(Calendar.DAY_OF_MONTH)+"."+data.get(Calendar.MONTH)+"."+data.get(Calendar.YEAR)+" godz: "+data.get(Calendar.HOUR)+":"+data.get(Calendar.MINUTE)+":"+data.get(Calendar.SECOND));            
        zapis.println();   

		connection = new Connection(socket);
		connection.start();

		return true;
	}

	public void stop() {
		if (connection != null)
			connection.close();
                    zapis.println("Zegar: " + zegarKlient.toString());
                    zapis.println();                               
                                                                zegarKlient.increment();
                                                                zapis.println("Zegar: " + zegarKlient.getLocalMax());
                                                                zapis.println("QUIT_CLIENT");     
                                                                zapis.println();                
                zapis.close();  
                
	}

	public String getPlayerID() {
		return playerID;
	}

	public void sendMessage(GameEvent ge) {
		connection.sendMessage(ge.toSend());
	}

        //odbiór wiadomości
	public GameEvent receiveMessage() {
		if (connection.messagesQueue.isEmpty()) {
			return null;
		} else {
			GameEvent ge = new GameEvent((String) connection.messagesQueue
					.getFirst());
			connection.messagesQueue.removeFirst();
			return ge;
		}
	}

	public boolean isAlive() {
		return (connection != null && connection.isAlive());
	}
}